package com.penglecode.netty.server;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;

import com.penglecode.netty.codec.protostuff.ProtostuffObjectDecoder;
import com.penglecode.netty.codec.protostuff.ProtostuffObjectEncoder;
import com.penglecode.protostuff.runtime.ObjectSerializer;
import com.penglecode.protostuff.runtime.ProtostuffSerializer;

public class NettyServerChannelPipelineFactory implements ChannelPipelineFactory {

	private ObjectSerializer serializer = new ProtostuffSerializer();
	
	private ExecutionHandler executionHandler;
	
	private ObjectMethodExecutor<?,?> objectMethodExecutor;
	
	public NettyServerChannelPipelineFactory() {
		super();
		this.executionHandler = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 4, 1048576, 1048576));
	}

	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline channelPipeline = Channels.pipeline();
		channelPipeline.addLast("serverdecoder", new ProtostuffObjectDecoder(serializer));
		channelPipeline.addLast("serverencoder", new ProtostuffObjectEncoder(serializer));
		channelPipeline.addLast("executiondandler", executionHandler);
		channelPipeline.addLast("serverHandler", new NettyServerHandler(objectMethodExecutor));
		return channelPipeline;
	}

	public void setExecutionHandler(ExecutionHandler executionHandler) {
		this.executionHandler = executionHandler;
	}

	public void setSerializer(ObjectSerializer serializer) {
		this.serializer = serializer;
	}

	public void setObjectMethodExecutor(
			ObjectMethodExecutor<?, ?> objectMethodExecutor) {
		this.objectMethodExecutor = objectMethodExecutor;
	}

}
